package com.xxl.job.admin.job;

import com.google.gson.Gson;
import com.mysql.cj.xdevapi.JsonValue;
import com.ruoyi.backups.domain.MysqlBacklog;
import com.ruoyi.backups.domain.MysqlBackups;
import com.ruoyi.backups.domain.OosConfig;
import com.ruoyi.backups.service.IMysqlBacklogService;
import com.ruoyi.backups.service.IMysqlBackupsService;
import com.ruoyi.backups.service.impl.OosConfigServiceImpl;
import com.ruoyi.common.sdk.connection.MySqlConnectionClient;
import com.ruoyi.common.sdk.oos.AliyunOosClient;
import com.xxl.job.admin.entity.BackupParams;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.DecimalFormat;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xiaoyan
 * @date 2024/9/9 下午8:39
 **/
@Component
public class DatabaseBackupJob {
    private final Logger log = LoggerFactory.getLogger(DemoJob.class);

    @Autowired
    private IMysqlBackupsService mysqlBackupsService;

    @Autowired
    private OosConfigServiceImpl oosConfigService;

    @Autowired
    private IMysqlBacklogService mysqlBacklogService;


    @XxlJob("databaseBackupJob")
    public void databaseBackupJobHandler() {
        String jobParam = XxlJobHelper.getJobParam();
        // 创建Gson实例
        Gson gson = new Gson();
        Map<String, String> params = gson.fromJson(jobParam, Map.class);
        Long oosId = Long.valueOf(params.get("oosId"));
        Long dataId = Long.valueOf(params.get("dataId"));

        if (oosId == null) {
            log.info("OOSID is null：请重新输入！");
            return;
        }
        if (dataId == null) {
            log.info("DATAID is null：请重新输入！");
            return;
        }
        //查找数据源
        MysqlBackups mysqlBackups = mysqlBackupsService.selectMysqlBackupsById(dataId);
        if (mysqlBackups == null) {
            log.info("mysqlBackups is null 请输入正确的DATAID!");
            return;
        }
        OosConfig oosConfig = oosConfigService.selectOosConfigById(oosId);
        if (oosConfig == null) {
            log.info("oosConfig is null 请输入正确的OOSID！");
            return;
        }
        //构建连接
        log.info("----------Begin：导出任务----------");
        MySqlConnectionClient mySqlConnectionClient = new MySqlConnectionClient.Builder()
                .mySqlIp(mysqlBackups.getMysqlIp())//Ip
                .mySqlPort(mysqlBackups.getMysqlPort())//端口
                .databaseName(mysqlBackups.getDatabaseName())//数据库名
                .databasePassword(mysqlBackups.getDatabasePassword())//数据库密码
                .databaseUsername(mysqlBackups.getDatabaseUsername())//数据库用户名
                .build();

        //导出脚本
        //拿到脚本位置
        String Sqlpath = mySqlConnectionClient.backupDB();

        log.info("----------导出脚本完毕----------");
        //上传到OOS
        AliyunOosClient aliyunOosClient = new AliyunOosClient.Builder()
                .accessKeyId(oosConfig.getAccessKey())
                .bucketName(oosConfig.getBucketName())
                .endpoint(oosConfig.getEndpoint())
                .accessKeySecret(oosConfig.getAccessSecret()).build();

        File file=new File(Sqlpath);
        String name = file.getName();
        log.info("----------上传阿里云----------");
        aliyunOosClient.uploadFileToOSS(Sqlpath,mysqlBackups.getDatabaseName()+"/"+name);
//        https://sql-bach.oss-cn-beijing.aliyuncs.com/scdl/scdl-20240909152744.sql
//        https://oss-cn-beijing.aliyuncs.com

        //插入日志
        String endpoint = oosConfig.getEndpoint();
        String url2 = endpoint.replace("https://", "");
        String bucketName = oosConfig.getBucketName();
        String url = "https://"+bucketName+"."+url2+"/"+mysqlBackups.getDatabaseName()+"/"+name;

        MysqlBacklog mysqlBacklog=new MysqlBacklog();
        mysqlBacklog.setMysqlId(dataId.toString());
        mysqlBacklog.setOosId(oosId.toString());
        mysqlBacklog.setFileEndpoint(url);

        // 获取文件大小（以字节为单位）
        long fileSizeInBytes = file.length();
        // 将字节转换为兆字节
        double fileSizeInMB = fileSizeInBytes / (1024.0 * 1024);
        // 格式化输出结果，精确到小数点后两位
        DecimalFormat df = new DecimalFormat("#.00");
        String formattedSize = df.format(fileSizeInMB);
        mysqlBacklog.setFileSize(formattedSize+"MB");
        mysqlBacklog.setFilePath(file.getPath());
        mysqlBacklogService.insertMysqlBacklog(mysqlBacklog);
        log.info("----------任务执行完成----------");
    }
}
